package com.mlz.mlzmall.ui.activity.act.address;

import android.content.Context;
import android.content.res.AssetManager;

import org.json.JSONArray;
import org.json.JSONObject;

import java.io.InputStream;

/**
 * 根据地址码获取省市县
 * Created by jack.wang on 2016/3/9.
 */
public class postCodeToPCD {
    JSONArray arrayProv;
    JSONObject jsonCity,jsonDistrict;
    public postCodeToPCD(Context activity)
    {
        AssetManager assetManager = activity.getResources().getAssets();
        try {
            StringBuffer buffer = new StringBuffer();
            InputStream inputStream = assetManager.open("postcode.json");
            byte[] data = new byte[1024 * 4];

            while (inputStream.read(data) != -1) {
                String jj = new String(data);
                buffer.append(jj);
            }
            inputStream.close();
            String string = buffer.toString();
            JSONObject object = new JSONObject(string);
            arrayProv = object.optJSONArray("province");

        } catch (Exception e) {
            System.out.println("gggg++" + e.toString());
        }
    }
    public String province(String strPCode) {
       String province = "";
                if (!strPCode.equals("")) {
                    strPCode = strPCode.substring(0, 2).trim() + "0000";
                    for (int i = 0; i < arrayProv.length(); i++) {
                        JSONObject object = arrayProv.optJSONObject(i);
                        if(object.optString("code").equals(strPCode)){
                            province = object.optString("name");
                            jsonCity = object;
                            return province;
                        }
                    }
                }
        return province;
    }

    public String city(String strPCode) {
        String city ="";
        if (!strPCode.equals("")) {
            strPCode = strPCode.substring(0, 4).trim() + "00";
            JSONArray jsonArray = jsonCity.optJSONArray("city");
            for (int i = 0; i < jsonArray.length(); i++) {
                JSONObject object1 = jsonArray.optJSONObject(i);
                if(object1.optString("code").equals(strPCode)){
                    city = object1.optString("name");
                    jsonDistrict = object1;
                    return city;
                }
            }
        }
        return city;

    }
    public String district(String strPCode) {
        String district = "";
        if (!strPCode.equals("")) {
            JSONArray jsonArray = jsonDistrict.optJSONArray("area");
            for (int i = 0; i < jsonArray.length(); i++) {
                JSONObject object = jsonArray.optJSONObject(i);
                if(object.optString("code").equals(strPCode)){
                    district = object.optString("name");
                    return district;
                }
            }
        }
        return district;


    }

}
